$(function(){

	$("#functionNav").attr("href",navAddr);
	String.prototype.trim=function(){
	   return this.replace(/(^\s*)|(\s*$)/g, "");
	}
	
	var cpflCols, cpjbCols, bgbmCols;
	var cpflJson, cpjbJson, cpsdJson, bgbmJson;
	
	var data;
	
	var searchParams = $("#stat-form").serializeObject();
	if(searchParams.zxbz)
		searchParams.zxbz=1;
	else
		searchParams.zxbz=0;
	var x = searchParams.x;
	var y = searchParams.y;
	var tableColumn = createColumn(searchParams);
	
	initSelect();
	
	//必须在initSelect()之后调用
	initTableHead();
	
	initTableFoot();
	
	createTable();
//	createTableWithOutPage('#stat-show', ProjectName+'/colstat.getCollectionTotal.do', y, tableColumn, searchParams);
	
	//统计查询点击事件监听
	$('#stat-cp-query').click(function(){
		searchParams = $("#stat-form").serializeObject();
		if(searchParams.zxbz)
			searchParams.zxbz=1;
		else
			searchParams.zxbz=0;
		x = searchParams.x;
		y = searchParams.y;
		if(x==y){
			alertFunc("横纵坐标不能相同！");
			return;
		}
		tableColumn = createColumn(searchParams);
		initTableHead();
		initTableFoot();
		createTable();
	});
	
	//文件导出点击事件监听
	$('#stat-cp-export').click(function(){
		searchParams.title = $('#table-head').html();
		searchParams.author = userInfo.username;
		searchParams.type = 'cpzltj';
		
//		ajaxResult("post", false, ProjectName+'/colstat.export.do', searchParams);
		
		$.fileDownload(ProjectName+'/colstat.export.do', {
			data: $.param(searchParams),
			httpMethod: "post",
			successCallback: function (url) {
				console.log('文件下载成功！')
			},
			failCallback: function (responseHtml, url, error) { 
				console.log('文件下载失败！')
			}
		});
		
	});
	
	//获取统计数据，并填充到表格
	function createTable(){
		//导出按钮设为不可用
		$('#stat-cp-export').attr('disabled', true);
		
		$('#stat-show').bootstrapTable('destroy');		
		$('#stat-show').bootstrapTable({
			url: ProjectName+'/colstat.getCollectionTotal.do',
			method: 'get',
			sidePagination: "server",
			queryParams: searchParams,
			columns: tableColumn,
			onLoadSuccess: function(d){  //加载成功时执行  
	             data=d;
	             //导出按钮可用
	             $('#stat-cp-export').attr('disabled', false);
	        },
	        onLoadError: function(d){
	        	console.log(d)
	        }
		});
	};
	
	//判断字符串是否非空，且不为空字符串
	function isValidStr(str){
		if(str && str.trim().length>0)
			return true;
		return false;
	}
	
	//初始化下拉列表项
	function initSelect(){
		cpflJson = ajaxResult("get",false,ProjectName+"/sysmanage.getIdNameByParentid.do", {"tableName":'jb_cplb', 'parentid':'0'});
		cpflJson = cpflJson.rows;
		loadSelect("#cpfl",cpflJson,'id','name');
		cpjbJson = ajaxResult("get",false,ProjectName+"/sysmanage.getIdAndNameInJb.do", {"tableName":'jb_cpjb'});
		cpjbJson = cpjbJson.rows;
		loadSelect("#cpjb",cpjbJson,'id','name');
		cpsdJson = ajaxResult("get",false,ProjectName+"/sysmanage.getIdNameByParentid.do", {"tableName":'jb_nd', 'parentid':'0'});
		cpsdJson = cpsdJson.rows;
		loadSelect("#cpsd",cpsdJson,'id','name');
		bgbmJson = ajaxResult("get",false,ProjectName+"/sysmanage.getIdAndNameInJb.do", {"tableName":'jb_bgbm'});
		bgbmJson = bgbmJson.rows;
		loadSelect("#bgbm",bgbmJson,'id','name');
	}
	
	//初始化表标题
	function initTableHead(){
		var html = '藏品总量统计';
		var con = '';
		for(var key in searchParams){
			var value = searchParams[key];
			
			if(!isValidStr(value+""))
				continue;
			if(key == 'cpsd')
				con += '藏品时代：'+cpsdJson[index(cpsdJson, value)].name+'；'
			if(key == 'cpfl')
				con += '藏品分类：'+cpflJson[index(cpflJson, value)].name+'；'
			if(key == 'cpjb')
				con += '藏品级别：'+cpjbJson[index(cpjbJson, value)].name+'；'
			if(key == 'bgbm')
				con += '保管部门：'+bgbmJson[index(bgbmJson, value)].name+'；'
			if(key == 'zxbz' && value==1)
				con += '包含注销：是；'
		}
		if(con)
			html += ' ( ' + con + ' )';
		$('#table-head').html(html);
	}
	
	//初始化表脚注
	function initTableFoot(){
		//获取用户信息
		if(!userInfo)
			getUserRight();
		
		var content = "";
		content += '制表人：'+userInfo.username+'<br>';
		content += '统计时间：'+nowDate();
		
		$('#table-foot').html(content);
	}
	
	//获取指定id值的下标索引
	//arr的格式：[{id:diancangbu, name:'典藏部'}, ...]
	function index(arr, key){
		var i = -1;
		$.each(arr, function(index, item){
			if(item.id==key){
				i = index;
				return false;
			}
		});
		return i;
	}

	//生成table第一行的列头
	function createColumn(paras){
		var enToCn = {'cpfl':'藏品分类', 'cpjb':'藏品级别', 'bgbm':'保管部门'};
		var cols, tableName;
		//x向是否加了过滤条件
		var conditionOnX = false;
		//过滤条件值
		var conditionX = "";
		
		var x_=paras.x;
		var y_=paras.y;
		if(x_=="cpfl"){
			conditionOnX = isValidStr(paras.cpfl);
			conditionX = paras.cpfl;
			if(cpflCols)
				cols = cpflCols;
			else
				tableName = "jb_cplb";
			
		}else if(x_=="cpjb"){
			conditionOnX = isValidStr(paras.cpjb);
			conditionX = paras.cpjb;
			if(cpjbCols)
				cols = cpjbCols;
			else
				tableName = "jb_cpjb";
			
		}else{
			conditionOnX = isValidStr(paras.bgbm);
			conditionX = paras.bgbm;
			console.log(bgbmCols)
			if(bgbmCols){
				cols = bgbmCols;
				//此处遍历的是数组
				$.each(cols, function(index){
					if(cols[index].field==conditionX){
						conditionX = index;
						return;
					}
				});
			}else
				tableName = "jb_bgbm";
		}
		
		//如果cols非空，则使用缓存
		if(cols){
			//使用了缓存，缓存cols的第一列是上次查询使用的y向指标
			//当y向变动时，需更换第一列
			if(cols[0]['field']!=y_){
				cols.shift();
				var firstCol = {};
				firstCol['field'] = y_;
				firstCol['align'] = 'center';
				firstCol['title'] = enToCn[y_];
				cols.unshift(firstCol);
			}
			//如果在x横向添加了条件过滤，则只显示条件列
			if(conditionOnX){
				var newCols = [];
				newCols.push(cols[0]);
				newCols.push(cols[conditionX]);
				cols = newCols;
			}
			return cols;
		}
		//否则，请求后台，获取列
		cols = ajaxResult("get",false,ProjectName+"/colstat.getCollectionTotalCols.do", {"tableName":tableName, "type":x_});
		cols = cols.data;
		
		//生成列，即表格第一行的列名
		var tColumn = [];
		var firstCol = {};
		firstCol['field'] = y_;
		firstCol['align'] = 'center';
		firstCol['title'] = enToCn[y_];
		tColumn.push(firstCol);
		for(var key in cols){
			map = {}
			map['field'] = key;
			map['title'] = cols[key];
			map['align'] = 'center';
			tColumn.push(map);
		}
		
		//设置缓存，在非刷新时有效。只要刷新页面，缓存则消失。
		if(x_=="cpfl") cpflCols = tColumn;
		else if(x_=="cpjb") cpjbCols = tColumn;
		else bgbmCols = tColumn;
		
		//若有x向条件过滤，则只返回条件指定的列，否则返回所有列
		if(conditionOnX){
			//保管部门的列key值不是数字索引，需要转换
			//藏品分类和藏品级别的均为数字，所以无需转换
			if(x_=="bgbm"){
				//cols样子:  {shuhuabu: "书画部", diancangbu: "典藏部", ziranbu: "自然部"}
				//从1开始计数。因为tColumn第0列是列头，正式内容从1开始。
				var i = 1; 
				//此处遍历的是map
				$.each(cols, function(key){ //key类似为shuhuabu
					if(key==conditionX){
						conditionX = i;
						return;
					}
					i++;
				});
			}
			
			var newCols = [];
			newCols.push(tColumn[0]);
			newCols.push(tColumn[conditionX]);
			tColumn = newCols;
		}
		
		return tColumn;
	}
});